extends Node2D


var viewWidth
var viewHeight = 320
var windowWidth
var windowHeight
var windowAspectRatio:float
var widthRegion = 160
var heightRegion = 320
var otherPlayerViewInited = false
var otherPlayerViewDict = {}

@onready var mainTetrisRegion:TetrisRegion = $TetrisRegion
@onready var otherPlayerViewTexturesRoot = $OtherPlayerViewTextures
@onready var otherPlayerViewsRoot = $OtherPlayerViews


func _ready():
	MainGameButtons.setMode(true)
	MainGameMultiPlayerUi.hideExitGameToast()
	MainGameMultiPlayerUi.hideGameEndPanel()
	MainGameMultiPlayerUi.setVisible(true)
	
	GlobalSignals.SCORE_GETTED.connect(SCORE_GETTED_handler)
	GlobalSignals.MAIN_GAME_BUTTON_UPPER_TRIGGER.connect(MAIN_GAME_BUTTON_UPPER_TRIGGER_handler)
	GlobalSignals.MAIN_GAME_BUTTON_LEFT_TRIGGER.connect(MAIN_GAME_BUTTON_LEFT_TRIGGER_handler)
	GlobalSignals.MAIN_GAME_BUTTON_RIGHT_TRIGGER.connect(MAIN_GAME_BUTTON_RIGHT_TRIGGER_handler)
	GlobalSignals.MAIN_GAME_BUTTON_DOWN_TRIGGER.connect(MAIN_GAME_BUTTON_DOWN_TRIGGER_handler)
	GlobalSignals.GAME_END.connect(GAME_END_handler)
	GlobalSignals.GAME_CONTINUE.connect(GAME_CONTINUE_handler)
	GlobalSignals.NM_UPDATE_OTHER_PLAYER_VIEW.connect(NM_UPDATE_OTHER_PLAYER_VIEW_handler)
	GlobalSignals.NM_GET_ROOMINFO_RESULT.connect(NM_GET_ROOMINFO_RESULT_handler)
	GlobalSignals.NM_USER_SCORE_CHANGED.connect(NM_USER_SCORE_CHANGED_handler)
	GlobalSignals.MAIN_VIEW_CHANGED.connect(MAIN_VIEW_CHANGED_handler)

	autoAdapt()
	
	Global.score = 0
	GlobalSignals.UPDATE_SCORE_VIEW.emit()
	
	mainTetrisRegion.startGame()
	SoundManager.playMusic(SoundManager.GAMING_BG)

	NetMessages.getCurrentRoomInfo()
	

func NM_GET_ROOMINFO_RESULT_handler(data):
	Global.setCurrentRoomData(data["room"])
	if otherPlayerViewInited == false:
		otherPlayerViewInited = true
		initOtherPlayerView(Global.currentRoom)


func autoAdapt():
	var windowSize:Vector2i = DisplayServer.window_get_size()
	
	if Global.isOSWindows():
		windowWidth = windowSize.x
		windowHeight = windowSize.y
	else:
		windowWidth = windowSize.y
		windowHeight = windowSize.x
	
	windowAspectRatio = windowWidth * 1.0 / windowHeight
	viewWidth = windowWidth * viewHeight / windowHeight 
	
	var debugMessage = "windowWidth: %s\nwindowHeight: %s\nwindowAspectRatio: %s\nviewWidth: %s\nviewHeight: %s\nosName: %s" % [windowWidth, windowHeight, windowAspectRatio, viewWidth, viewHeight, OS.get_name()]
	GlobalSignals.DEBUG_MESSAGE.emit(debugMessage)
	
	mainTetrisRegion.setPos(Vector2(viewWidth / 2 - mainTetrisRegion.getSize().x / 2, 0))
	
	
func _exit_tree():
	SoundManager.stopAllMusic()
	
	MainGameMultiPlayerUi.setVisible(false)
	MainGameButtons.visible = false
	
	GlobalSignals.SCORE_GETTED.disconnect(SCORE_GETTED_handler)
	GlobalSignals.MAIN_VIEW_CHANGED.disconnect(MAIN_VIEW_CHANGED_handler)
	GlobalSignals.NM_USER_SCORE_CHANGED.disconnect(NM_USER_SCORE_CHANGED_handler)
	GlobalSignals.NM_UPDATE_OTHER_PLAYER_VIEW.disconnect(NM_UPDATE_OTHER_PLAYER_VIEW_handler)
	GlobalSignals.NM_GET_ROOMINFO_RESULT.disconnect(NM_GET_ROOMINFO_RESULT_handler)
	GlobalSignals.GAME_CONTINUE.disconnect(GAME_CONTINUE_handler)
	GlobalSignals.GAME_END.disconnect(GAME_END_handler)
	GlobalSignals.MAIN_GAME_BUTTON_UPPER_TRIGGER.disconnect(MAIN_GAME_BUTTON_UPPER_TRIGGER_handler)
	GlobalSignals.MAIN_GAME_BUTTON_LEFT_TRIGGER.disconnect(MAIN_GAME_BUTTON_LEFT_TRIGGER_handler)
	GlobalSignals.MAIN_GAME_BUTTON_RIGHT_TRIGGER.disconnect(MAIN_GAME_BUTTON_RIGHT_TRIGGER_handler)
	GlobalSignals.MAIN_GAME_BUTTON_DOWN_TRIGGER.disconnect(MAIN_GAME_BUTTON_DOWN_TRIGGER_handler)
	
	
func NM_USER_SCORE_CHANGED_handler(data):
	var userId = data["user"]["userId"]
	var score = data["score"]
	if otherPlayerViewDict.has(userId):
		var targetView:OtherPlayerView = otherPlayerViewDict[userId] as OtherPlayerView
		targetView.updateScore(score)
	
	
func SCORE_GETTED_handler(data):
	Global.score += data
	GlobalSignals.UPDATE_SCORE_VIEW.emit()
	NetMessages.sendScoreChanged()
	

func MAIN_VIEW_CHANGED_handler():
	sendUpdateViewToOthers()

	
func MAIN_GAME_BUTTON_UPPER_TRIGGER_handler():
	mainTetrisRegion.onButtonUpperTrigger()


func MAIN_GAME_BUTTON_LEFT_TRIGGER_handler():
	mainTetrisRegion.onRapidButtonLeftTrigger()


func MAIN_GAME_BUTTON_RIGHT_TRIGGER_handler():
	mainTetrisRegion.onRapidButtonRightTrigger()


func MAIN_GAME_BUTTON_DOWN_TRIGGER_handler():
	mainTetrisRegion.onRapidButtonDownTrigger()
	

func GAME_CONTINUE_handler():
	mainTetrisRegion.gameContinue()	


func GAME_END_handler():
	mainTetrisRegion.gameEnd()
	sendGameEndNM()
	

func sendGameEndNM():
	NetMessages.sendUserGameEnd()
	
	
func NM_UPDATE_OTHER_PLAYER_VIEW_handler(data):
	var userData = data["user"]
	var blocksData = data["blocksData"]
	
	var userId = userData["userId"]
	if otherPlayerViewDict.has(userId):
		var targetView:OtherPlayerView = otherPlayerViewDict[userId] as OtherPlayerView
		targetView.setUser(userData)
		targetView.updateView(blocksData)
	

func sendUpdateViewToOthers():
	var data = {
		"blocksData": mainTetrisRegion.getBlocksData()
	}	
	NetClient.sendMessage(NetMessages.NM_SEND_UPDATE_VIEW, data)
	

func initOtherPlayerView(room):
	var users:Array = room["users"]
	var otherUserCount = users.size() - 1
	
	if otherUserCount <= 0:
		return
	
	var leftViewCount = (otherUserCount - 1) / 2 + 1
	var rightViewCount = otherUserCount - leftViewCount
	
	var sideContainerWidth = (viewWidth - widthRegion) / 2
	var sideContainerHeight = viewHeight
	
	var leftSideViewArr = []
	var rightSideViewArr = []
	var viewTexturesArr = []
	
	if leftViewCount > 0:
		leftSideViewArr = intelligentLayout(sideContainerWidth, sideContainerHeight, leftViewCount)
	
	if rightViewCount > 0:
		rightSideViewArr = intelligentLayout(sideContainerWidth, sideContainerHeight, rightViewCount)
		for viewElement in rightSideViewArr:
			viewElement["x"] += (sideContainerWidth + widthRegion)
	
	if leftSideViewArr.size() > 0:
		for view in leftSideViewArr:
			var inst:OtherPlayerViewTexture = Global.createSceneInst("OtherPlayerViewTexture") as OtherPlayerViewTexture
			otherPlayerViewTexturesRoot.add_child(inst)
			inst.init(view["x"], view["y"], view["width"], view["height"])
			viewTexturesArr.append(inst)
	
	if rightSideViewArr.size() > 0:
		for view in rightSideViewArr:
			var inst:OtherPlayerViewTexture = Global.createSceneInst("OtherPlayerViewTexture") as OtherPlayerViewTexture
			otherPlayerViewTexturesRoot.add_child(inst)
			inst.init(view["x"], view["y"], view["width"], view["height"])
			viewTexturesArr.append(inst)
			
	otherPlayerViewDict = {}
	var index = 0
	for user in users:
		if user["userId"] == Global.currentUser["userId"]: continue
		var inst:OtherPlayerView = Global.createSceneInst("OtherPlayerViewport") as OtherPlayerView
		otherPlayerViewsRoot.add_child(inst)
		inst.setUser(user)
		otherPlayerViewDict[user["userId"]] = inst
		
		var targetViewTexture:OtherPlayerViewTexture = viewTexturesArr[index]
		index += 1
		targetViewTexture.setViewTexture(inst.getViewportTexture())
	

func intelligentLayout(containerWidth, containerHeight, count):
	return Global.intelligentLayout(containerWidth, containerHeight, count)
	
	
	

